//
//  HMTabBar.swift
//  Weibo
//
//  Created by mac on 2017/6/4.
//  Copyright © 2017年 mac. All rights reserved.
//

import UIKit

protocol HMTabBarDelegate:NSObjectProtocol {
    
    func composeOperation()
}

//自定义tabbar
class HMTabBar: UITabBar{
    var composeCallBack:(()->())?
    weak var hmDelegate:HMTabBarDelegate?
    //懒加载控
    //这是中间的按钮按钮
    private lazy var composeBUtton:UIButton={
        let button = UIButton()
        button.addTarget(self, action: #selector(composeButtonAction), for: .touchUpInside)
        //设置不同状态下的背景图片
        button.setBackgroundImage(UIImage(named:"tabbar_compose_button"), for: UIControlState.normal)
        button.setBackgroundImage(UIImage(named:"tabbar_compose_button_highlighted"), for: UIControlState.highlighted)
    
        //设置不同状态的图片
        button.setImage(UIImage(named:"tabbar_compose_icon_add"), for:.normal)
        button.setImage(UIImage(named:"tabbar_compose_icon_add_highlighted"), for:.highlighted)
        
        //设置和内容一样大--自适应
        button.sizeToFit()
        
        return button
    }()
    
    //创建视图的时候添加按钮
    
    override init(frame:CGRect){
        
        super.init(frame: frame)
        setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
        super.init(coder: aDecoder)
        setupUI()
    }
    
    //添加控件
    private func setupUI(){
        addSubview(composeBUtton)
        
        //backgroundColor=UIImage(named:"tabbar_background")
           }
    
   
    @objc private func composeButtonAction(){
        composeCallBack?()
    }
    
   

    //调整子控件布局
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        composeBUtton.centerX=width*0.5
        composeBUtton.centerY=height*0.5
        
        //计算每项按钮的宽度
        let buttonW = width/5
        
        var index = 0
        
        for subView in self.subviews {
            if subView.isKind(of: NSClassFromString("UITabBarButton")!) {
                subView.width=buttonW
                subView.x=CGFloat(index)*buttonW
                index += 1
                if index==2 {
                    index += 1
                }
            }
        }
        
        
        
        
    }
    
    
    
    
    
}
